// 默认缓存期限为15天
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 15;

/**
 * 创建本地缓存对象
 * @param {string=} prefixKey
 */
export const createStorage = ({ prefixKey = '' } = {}) => {
	/**
	 * 本地缓存类
	 * @class Storage
	 */
	const Storage = class {
		getKey(key) {
			return `${prefixKey}${key}`;
		}

		/**
		 * @description 设置缓存
		 * @param {string} key 缓存键
		 * @param {*} value 缓存值
		 * @param expire
		 */
		setData(key, value, expire = DEFAULT_CACHE_TIME) {
			const stringData = {
				value,
				expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
			};
			uni.setStorageSync(this.getKey(key), stringData);
		}

		/**
		 * 读取缓存
		 * @param {string} key 缓存键
		 * @param {*=} def 默认值
		 */
		getData(key, def) {
			const item = uni.getStorageSync(this.getKey(key));
			if (item) {
				try {
					const data = item;
					const { value, expire } = data;
					// 在有效期内直接返回
					if (expire === null || expire >= Date.now()) {
						return value;
					}
					this.removeData(this.getKey(key));
				} catch (e) {
					return def;
				}
			}
			return def;
		}

		/**
		 * 从缓存删除某项
		 * @param {string} key
		 */
		removeData(key) {
			uni.removeStorageSync(this.getKey(key));
		}

		/**
		 * 清空所有缓存
		 * @memberOf Cache
		 */
		clearData() {
			uni.clearStorageSync();
		}
	};
	return new Storage();
};

export const Storage = createStorage();
